package com.zzz.gp.aspect;


import com.alibaba.fastjson.JSONObject;
import com.zzz.gp.bean.LogRecord;
import com.zzz.gp.enums.ReturnCodeEnum;
import com.zzz.gp.exception.DONotAlarmException;
import com.zzz.gp.service.LogSave;
import com.zzz.gp.utils.RespUtil;
import com.zzz.gp.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: ZZZ
 * @time: 2021/2/24 17:45
 */
@Slf4j
@Order(1)
@Component
public class RecordAspect {

    @Autowired
    private LogSave logSave;

    @Pointcut("execution(public * com.zzz.gp..*Controller.*(..))")
    public void executionMethod() {
    }

    @Around(value = "executionMethod()")
    public Object logAspect(ProceedingJoinPoint pjp) throws Throwable {

        LogRecord logRecord = new LogRecord();

        log.info("===进入日志切面类===");
        Object[] params = pjp.getArgs();
        String bsn = "";
        String bizType = "";
        if (params != null && params.length > 0) {
            String requestParam = JSONObject.toJSONString(params[0]);
            logRecord.setRequestStr(requestParam);
            JSONObject json = JSONObject.parseObject(requestParam);
            if (json != null && json.containsKey("bsn") && json.getString("bsn") != null) {
                bsn = json.getString("bsn");
            }
            if (json != null && json.containsKey("bizType") && json.getString("bizType") != null) {
                bizType = json.getString("bizType");
                logRecord.setBizType(bizType);
            }
        }
        Object result = null;
        try {
            result = pjp.proceed();
            logRecord.setResponseStr(JSONObject.toJSONString(result));
        } catch (Exception e) {
            System.out.println("日志结束:exception " + e.getMessage());
            if (e instanceof DONotAlarmException) {
                ReturnCodeEnum returnCodeEnumByCode = ReturnCodeEnum.getReturnCodeEnumByCode(((DONotAlarmException) e).getCode());
                String code = returnCodeEnumByCode.getCode();
                String message = e.getMessage();
                if (StringUtils.isBlank(message)) {
                    message = returnCodeEnumByCode.getMessage();
                }
                result = RespUtil.commonResp(code, message, bsn, result);
                return result;
            }
            result = RespUtil.commonResp(ReturnCodeEnum.REQUEST_FAIL.getCode(), ReturnCodeEnum.REQUEST_FAIL.getMessage(), bsn, result);
        }

        logSave.save(logRecord);
        return result;

    }


}
